package io;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;

/**
 * 字符输入流测试
 */
public class FileInputStreamTest {
    public static void main(String[] args) {
//        readOneByte();
//        readBytes();
        copyFile();
    }

    /**
     * 读取一个字节
     */
    static void readOneByte() {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("/Users/luchuan/IdeaProjects/java-test/a.txt");
            for (int i = 0; i < 10; i++) {
                int read = fis.read(); //读到文件末尾返回-1
                System.out.println("read = " + read);
            }

            /**
             * '你'测试
             * 读到的字节和原有字节不一样 read [228,189,160] byte [-28,-67,-96]
             * byte的最大值是127，int的128转为byte就变成了-128，int的228变成byte之后就成-28
             */
            System.out.println(Arrays.toString("你".getBytes("UTF-8")));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 读取多个字节
     */
    static void readBytes() {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("/Users/luchuan/IdeaProjects/java-test/a.txt");
            byte[] bytes = new byte[1024];
            int len;
            while ((len = fis.read(bytes)) != -1) {
                System.out.println(new String(bytes, 0, len));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 复制文件
     */
    static void copyFile() {
        /**
         * JDK7新特性：try后边可以跟一个(),括号内可以定义流对象
         * 那么这个流对象的作用域在try中有效
         * try中的代码执行完毕，会自动释放流对象
         */
        try (
                FileInputStream fis = new FileInputStream("/Users/luchuan/IdeaProjects/java-test/a.txt");
                FileOutputStream fos = new FileOutputStream("/Users/luchuan/IdeaProjects/java-test/a_copy.txt");
        ) {
            byte[] bytes = new byte[1024];
            int len;
            while ((len = fis.read(bytes)) != -1) {
                fos.write(bytes, 0, len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
